package org.example.clouddemo.order.service.common.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.clouddemo.bean.common.Param.UpdateProductParam;
import org.example.clouddemo.bean.common.Param.UserAppVo;
import org.example.clouddemo.order.OrderStatus;
import org.example.clouddemo.order.feign.UserFeignClient;
import org.example.clouddemo.order.service.common.OrderService;
import org.example.clouddemo.bean.common.entity.Order;
import org.example.clouddemo.bean.common.entity.Product;
import org.example.clouddemo.order.feign.ProductFeignClient;
import org.example.clouddemo.order.service.common.mapper.OrderServiceMapper;

import org.example.common.bean.LoginUser;
import org.example.common.response.ApiResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@RequiredArgsConstructor
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    private final ProductFeignClient productFeignClient;
    private final UserFeignClient userFeignClient;

    private final OrderServiceMapper orderServiceMapper;

    /**
     * 创建订单
     * @param order 订单对象
     * @return 订单id
     */
    @Override
    public String  createOrder (Order order){
        // 判断传入的Order对象是否符合要求
        if (!extracted(order).equals("false")) return extracted(order);

        // 查询指定产品
        Product product = new Product();
        product.setId(order.getProductId()); // 产品ID
        // 在需要进行远程调用的服务类或控制器中注入Feign客户端 如productFeignClient 调用远程服务
        ApiResult<Product> apiResult = productFeignClient.queryOne(product);
        Product data = apiResult.getData(); // 得到产品信息

        if (data == null) {
            log.info("没有这个商品");
            return OrderStatus.PRODUCT_NOT_EXIST.getDesc();
        }


        Integer totalPrice = data.getPrice() * order.getQuantity(); // 计算总价
        Long orderId = IdUtil.getSnowflake().nextId(); // 生成填充订单id


        // 包装
        order.setId(orderId);
        order.setTotalPrice(totalPrice);
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        order.setStatus(OrderStatus.CREATED.getDesc());

        // 插入数据库表
        if(orderServiceMapper.insert(order)){
            log.info("订单创建成功,订单ID:"+ order.getId());
            return OrderStatus.ORDER_SUCCESS.getDesc() + order.getId().toString();}
        else{
            log.info("订单创建失败");
            return OrderStatus.ORDER_FAILED.getDesc();
        }

    }


//    /**
//     * 更新订单
//     * @param order 订单对象
//     * @return 改变结果
//     */
//    public String updateOrder (Order order){
//        // 判断传入的Order对象是否符合要求
//        if (!extracted(order).equals("false")) return extracted(order);
//
//        // 查询指定产品
//        Product product = new Product();
//        product.setId(order.getProductId()); // 产品ID
//        ApiResult<Product> apiResult = productFeignClient.queryOne(product);
//        Product data = apiResult.getData(); // 得到产品信息
//
//        if (data == null) {
//            log.info("没有这个商品");
//            return OrderStatus.PRODUCT_NOT_EXIST.getDesc();
//        }
//        if(data.getProductNum() - order.getQuantity() >= 0)
//            data.setProductNum(data.getProductNum() - order.getQuantity()); // 仓库中产品的数量
//        else
//        Integer totalPrice = data.getPrice() * order.getQuantity(); //总价
//
//
//        // 包装
//        order.setId(order.getId());
//        order.setTotalPrice(totalPrice);
//        order.setUpdateTime(LocalDateTime.now());
//
//        orderServiceMapper.updateById(order); // 插入数据库表
//
//        return order.getId();
//    }

    /**
     * 抽取用户参数
     * @param order 用户对象
     * @return 返回参数是否正确判断
     */
    private static String extracted (Order order){
        if (order.getUserId() == null) {
            log.info("用户ID为空");
            return OrderStatus.USER_ID_EMPTY.getDesc();
        }
        if (order.getProductId() == null) {
            log.info("商品ID为空");
            return OrderStatus.PRODUCT_ID_EMPTY.getDesc();
        }
        if (order.getQuantity() == null || order.getQuantity() <= 0) {
            log.info("购买数量<=0");
            return OrderStatus.QUANTITY_INVALID.getDesc();
        }
        return "false";
    }

    /**
     * 根据订单id来删除订单
     * @param id 订单id
     * @param loginUser 用户
     * @return 返回影响订单
     */
    @Override
    public int deleteByOrderId (Long id, LoginUser loginUser){
        //admin 有权限删除任意用户的订单
        if (loginUser.getUserType().equals("admin")) {
            return orderServiceMapper.deleteById(id);
        } else {
            Order order = orderServiceMapper.selectByUserIdAndOrderId(loginUser.getId(), id);
            if (order == null) {
                log.info("当前用户 ：{}没有订单ID为 :{}的订单", loginUser.getUserName(), id);
                return 0; // 不影响变化
            }
            return orderServiceMapper.deleteById(order.getId()); // 变化
        }

    }
    /**
     * 修改订单数量
     * @param order 订单对象
     * @return 修改结果
     */
    @Override
    public String updateQuantity(Order order) {
        //查询已存在订单
        Order order1 = orderServiceMapper.selectOneByOrderId(order.getId());
        if (order1 == null) {
            log.info("没有这个订单");
            return OrderStatus.RESULT_EMPTY.getDesc();
        }
        if(order1.getStatus().equals(OrderStatus.PAID.getDesc())){
            log.info("订单已支付,无法修改 ");
            return OrderStatus.PAID.getDesc()+OrderStatus.CANNOT_UPDATE_QUANTITY.getDesc();
        }
        //获取该订单的产品 假设产品价格已经发生变动
        //拿出产品id
        Product product = new Product();
        product.setId(order1.getProductId()); // 产品ID
        //远程调用
        ApiResult<Product> apiResult = productFeignClient.queryOne(product);

        Product data = apiResult.getData();
        if (data == null) {
            log.info("没有这个商品");
            return OrderStatus.PRODUCT_NOT_EXIST.getDesc();
        }

        //修改数量和总价格 不检查是否满足库存  在结算的时候再检查
        if(order.getQuantity()<=0)return OrderStatus.QUANTITY_INVALID.getDesc();
        order1.setTotalPrice(data.getPrice()*order.getQuantity());
        order1.setUpdateTime(LocalDateTime.now());
        order1.setQuantity(order.getQuantity());

        if(orderServiceMapper.updateById(order1)){
            log.info("订单修改成功");
            log.info(order1.toString());
            return OrderStatus.ORDER_SUCCESS.getDesc();
        }
        return OrderStatus.ORDER_FAILED.getDesc();
    }
    /**
     * 结算订单
     * @param order 订单对象
     * @return 结算结果
     */
    //开启事务
    @Transactional
    @Override
    public String settleOrder(Order order) {
        Order query = orderServiceMapper.selectByUserIdAndOrderId(order.getUserId(),order.getId());
        if (query == null) {
            log.info("没有这个订单");
            return OrderStatus.RESULT_EMPTY.getDesc();
        }
        if (query.getStatus().equals(OrderStatus.PAID.getDesc())) {
            log.info("订单已经支付无法结算");
            return OrderStatus.PAID.getDesc()+OrderStatus.CANNOT_SETTLE.getDesc();
        }
        if(query.getStatus().equals(OrderStatus.CANCELED.getDesc())){
            log.info("订单已经取消无法结算");
            return OrderStatus.CANCELED.getDesc()+OrderStatus.CANNOT_SETTLE.getDesc();
        }
        Product product = new Product();
        product.setId(query.getProductId()); // 产品ID
        //远程调用
        ApiResult<Product> apiResult = productFeignClient.queryOne(product);
        ApiResult<UserAppVo> userResult = userFeignClient.getInfo();
        UserAppVo user = userResult.getData();
        if (user == null) {
            log.info("没有这个用户");
            return OrderStatus.USER_NOT_EXIST.getDesc();
        }
        if (user.getMoney() < query.getTotalPrice()) {
            log.info("用户余额不足");
            return OrderStatus.INSUFFICIENT_BALANCE.getDesc()+OrderStatus.CANNOT_SETTLE.getDesc();
        }
        Product data = apiResult.getData();
        if (data == null) {
            log.info("没有这个商品");
            return OrderStatus.PRODUCT_NOT_EXIST.getDesc();
        }
        if(data.getProductNum()<query.getQuantity()){         // todo bug data.getProductNum() 可能为空
            log.info("库存不足");
            return OrderStatus.INSUFFICIENT_STOCK.getDesc()+OrderStatus.CANNOT_SETTLE.getDesc();
        }

        //更新库存
        data.setProductNum(data.getProductNum()-query.getQuantity());
        UpdateProductParam param= BeanUtil.copyProperties(data, UpdateProductParam.class);
        ApiResult<Integer> updateProduct = productFeignClient.update(param);
        //更新用户余额
        user.setMoney(user.getMoney()-query.getTotalPrice());
        ApiResult<Integer> updateUser = userFeignClient.update(user);
        //更新订单
        query.setStatus(OrderStatus.PAID.getDesc());
        query.setUpdateTime(LocalDateTime.now());
        boolean result = orderServiceMapper.updateById(query);
        if(updateUser.data>=1 && updateProduct.data>=1 && result)
            return  OrderStatus.ORDER_SUCCESS.getDesc();
        return OrderStatus.ORDER_FAILED.getDesc();
    }

    /**
     * 查询全部订单内容
     * @return 全部订单数据
     */
    @Override
    public List<Order> queryOrdersByAll() {
        return orderServiceMapper.selectAll();
    }

    /**
     * 基于用户ID获取订单
     * @param userId 用户id
     * @return 对应数据表
     */
    @Override
    public List<Order> getOrdersByUserId(Long userId){
        return orderServiceMapper.selectByUserId(userId);
    }

}
